package com.example.studentmanagement2.controller;

import com.example.studentmanagement2.model.Student;
import com.example.studentmanagement2.repository.Repository.StudentRepository;
import com.example.studentmanagement2.service.StudentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

import java.util.List;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public ResponseEntity<List<Student>> getAllStudents() {
        return ResponseEntity.ok(studentService.getAllStudents());
    }

    @PostMapping
    public ResponseEntity<Student> addStudent(@RequestBody Student student) {
        return new ResponseEntity<>(studentService.addStudent(student), HttpStatus.CREATED);
    }

    @PutMapping("/{originalId}")  // 路径参数为原始学号
    public ResponseEntity<Student> updateStudent(
            @PathVariable String originalId,  // 原始学号
            @RequestBody Student student      // 包含新学号的请求体
    ) {
        return ResponseEntity.ok(studentService.updateStudent(originalId, student));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable String id) {
        studentService.deleteStudent(id);
        return ResponseEntity.noContent().build();
    }
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable String id) {
        Optional<Student> student = studentService.getStudentById(id);  // 正确调用服务层方法
        return student.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
    @GetMapping("/search")
    public ResponseEntity<List<Student>> searchStudents(
            @RequestParam(required = false) String keyword
    ) {
        List<Student> students = studentService.searchStudents(keyword);
        return ResponseEntity.ok(students);
    }
     @GetMapping("/classes")
    public ResponseEntity<List<String>> getAllClasses() {
        try {
            List<String> classes = studentService.findDistinctClasses();
            return ResponseEntity.ok(classes);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}